package com.sun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.Result;
import com.sun.common.SystemCrmlog;
import com.sun.entity.Sale;
import com.sun.service.SaleService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/22 14:01
 * @FileName: SaleController
 * @Description: ""
 */
@Slf4j
@SuppressWarnings("all")
@RestController
@RequestMapping("/sale")
public class SaleController {

    @Autowired
    private SaleService saleService;

    //新增销售记录
    @SystemCrmlog(title = "销售管理模块", type = "INSERT", description = "新增销售记录")
    @RequiresAuthentication
    @PostMapping
    public Result<String> save(@RequestBody Sale sale) {
        saleService.save(sale);
        return Result.success("药品销售成功");
    }

    //修改销售记录
    @SystemCrmlog(title = "销售管理模块", type = "UPDATE", description = "修改销售记录")
    @RequiresAuthentication
    @PutMapping
    public Result<String> update(@RequestBody Sale sale) {
        saleService.updateById(sale);
        return Result.success("销售记录修改成功");
    }

    //删除销售记录
    @SystemCrmlog(title = "销售管理模块", type = "DELETE", description = "删除销售记录")
    @RequiresAuthentication
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        saleService.removeById(id);
        return Result.success("销售记录删除成功");
    }

    //分页查询所有的销售记录
    @RequiresAuthentication
    @GetMapping("page")
    public Result<Page> page(int pageNum, int pageSize, String drugName, String patientName,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<Sale> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(drugName != null, Sale::getDrugName, drugName);
        lambdaQueryWrapper.like(patientName != null, Sale::getPatientName, patientName);
        lambdaQueryWrapper.gt(startTime != null, Sale::getDateTime, startTime);
        lambdaQueryWrapper.lt(endTime != null, Sale::getDateTime, endTime);

        saleService.page(pageInfo, lambdaQueryWrapper);

        return Result.success(pageInfo);
    }


    /**
     * 按年月日统计每种药品的销售情况
     */
    //按年统计每种药品的销售情况（上个月结束的一年） 未测试 按年统计
    @GetMapping("/statisticsYear")
    public Result statisticsYear() {
        // 查询上个月结束的一年的起始日期和结束日期
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime lastMonthEndDate = currentDateTime.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime lastYearStartDate = lastMonthEndDate.minusYears(1).withMonth(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime lastYearEndDate = lastMonthEndDate.withHour(0).withMinute(0).withSecond(0).withNano(0);

        // 查询数据库获取上个月结束的一年内的销售记录
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.le(Sale::getDateTime, lastYearEndDate).ge(Sale::getDateTime, lastYearStartDate);
        List<Sale> saleRecords = saleService.list(lambdaQueryWrapper);

        // 统计销售记录
        Map<String, SaleStatistics> saleStatisticsMap = new HashMap<>();
        for (Sale record : saleRecords) {
            String drugName = record.getDrugName();
            Integer quantity = record.getNum();
            Double totalPrice = Double.valueOf(record.getTotalPrice());

            if (saleStatisticsMap.containsKey(drugName)) {
                SaleStatistics statistics = saleStatisticsMap.get(drugName);
                statistics.setQuantity(statistics.getQuantity() + quantity);
                statistics.setTotalPrice(statistics.getTotalPrice() + totalPrice);
            } else {
                SaleStatistics statistics = new SaleStatistics();
                statistics.setQuantity(quantity);
                statistics.setTotalPrice(totalPrice);
                saleStatisticsMap.put(drugName, statistics);
            }
        }

        // 将统计结果放到List中进行排序
        List<Map.Entry<String, SaleStatistics>> sortedStatistics = new ArrayList<>(saleStatisticsMap.entrySet());
        Collections.sort(sortedStatistics, new Comparator<Map.Entry<String, SaleStatistics>>() {
            @Override
            public int compare(Map.Entry<String, SaleStatistics> o1, Map.Entry<String, SaleStatistics> o2) {
                return o2.getValue().getQuantity().compareTo(o1.getValue().getQuantity());
            }
        });

        // 取前10个药品
        List<Map.Entry<String, SaleStatistics>> top20Statistics = sortedStatistics.subList(0, Math.min(sortedStatistics.size(), 10));

        return Result.success(top20Statistics);
    }

    //统计（上个月结束的一年）中每个月每种药品的销售情况  未测试
    @GetMapping("/statisticsEveryMonth")
    public Result statisticsEveryMonth() {
        // 获取当前日期
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 计算上个月的结束日期
        LocalDateTime lastMonthEndDate = currentDateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);

        // 查询数据库获取上个月到一年前的销售记录
        LocalDateTime oneYearAgo = currentDateTime.minusYears(1);
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.le(Sale::getDateTime, lastMonthEndDate).ge(Sale::getDateTime, oneYearAgo);
        List<Sale> saleRecords = saleService.list(lambdaQueryWrapper);

        // 统计销售记录
        Map<String, SaleStatistics> monthlySaleStatisticsMap = new HashMap<>();
        for (Sale record : saleRecords) {
            String monthYearKey = record.getDateTime().getMonth().toString() + record.getDateTime().getYear();
            String drugName = record.getDrugName();
            Integer quantity = record.getNum();
            Double totalPrice = Double.valueOf(record.getTotalPrice());

            String key = monthYearKey + "-" + drugName;

            if (monthlySaleStatisticsMap.containsKey(key)) {
                SaleStatistics statistics = monthlySaleStatisticsMap.get(key);
                statistics.setQuantity(statistics.getQuantity() + quantity);
                statistics.setTotalPrice(statistics.getTotalPrice() + totalPrice);
            } else {
                SaleStatistics statistics = new SaleStatistics();
                statistics.setQuantity(quantity);
                statistics.setTotalPrice(totalPrice);
                monthlySaleStatisticsMap.put(key, statistics);
            }
        }

        // 将统计结果放到List中进行排序
        List<Map.Entry<String, SaleStatistics>> sortedStatistics = new ArrayList<>(monthlySaleStatisticsMap.entrySet());
        Collections.sort(sortedStatistics, new Comparator<Map.Entry<String, SaleStatistics>>() {
            @Override
            public int compare(Map.Entry<String, SaleStatistics> o1, Map.Entry<String, SaleStatistics> o2) {
                return o2.getValue().getQuantity().compareTo(o1.getValue().getQuantity());
            }
        });

        // 取前20个药品
        List<Map.Entry<String, SaleStatistics>> top20Statistics = sortedStatistics.subList(0, Math.min(sortedStatistics.size(), 5));

        return Result.success(top20Statistics);
    }

    //按月份统计上个月每种药品的销售情况  未测试
    @GetMapping("/statisticsMonth")
    public Result statisticsMonth() {
        // 查询上个月的起始日期和结束日期
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime lastMonthStartDate = currentDateTime.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime lastMonthEndDate = currentDateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);

        // 查询数据库获取上个月的销售记录
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.le(Sale::getDateTime, lastMonthEndDate).ge(Sale::getDateTime, lastMonthStartDate);
        List<Sale> saleRecords = saleService.list(lambdaQueryWrapper);

        // 统计销售记录
        Map<String, SaleStatistics> saleStatisticsMap = new HashMap<>();
        for (Sale record : saleRecords) {
            String drugName = record.getDrugName();
            Integer quantity = record.getNum();
            Double totalPrice = Double.valueOf(record.getTotalPrice());

            if (saleStatisticsMap.containsKey(drugName)) {
                SaleStatistics statistics = saleStatisticsMap.get(drugName);
                statistics.setQuantity(statistics.getQuantity() + quantity);
                statistics.setTotalPrice(statistics.getTotalPrice() + totalPrice);
            } else {
                SaleStatistics statistics = new SaleStatistics();
                statistics.setQuantity(quantity);
                statistics.setTotalPrice(totalPrice);
                saleStatisticsMap.put(drugName, statistics);
            }
        }

        // 将统计结果放到List中进行排序
        List<Map.Entry<String, SaleStatistics>> sortedStatistics = new ArrayList<>(saleStatisticsMap.entrySet());
        Collections.sort(sortedStatistics, new Comparator<Map.Entry<String, SaleStatistics>>() {
            @Override
            public int compare(Map.Entry<String, SaleStatistics> o1, Map.Entry<String, SaleStatistics> o2) {
                return o2.getValue().getQuantity().compareTo(o1.getValue().getQuantity());
            }
        });

        // 取前10个药品
        List<Map.Entry<String, SaleStatistics>> top20Statistics = sortedStatistics.subList(0, Math.min(sortedStatistics.size(), 10));

        return Result.success(top20Statistics);
    }


    //统计上月每一天每种药品的销售情况 未测试
    @GetMapping("/statisticsEveryDay")
    public Result statisticsEveryDay() {
        // 获取当前日期
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 计算上月的开始日期和结束日期
        LocalDateTime lastMonthStartDate = currentDateTime.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime lastMonthEndDate = currentDateTime.withDayOfMonth(1).minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        // 查询数据库获取上月的销售记录
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.le(Sale::getDateTime, lastMonthEndDate).ge(Sale::getDateTime, lastMonthStartDate);
        List<Sale> saleRecords = saleService.list(lambdaQueryWrapper);

        // 统计销售记录
        Map<String, SaleStatistics> dailySaleStatisticsMap = new HashMap<>();
        for (Sale record : saleRecords) {
            String dayMonthYearKey = record.getDateTime().getDayOfMonth() + record.getDateTime().getMonth().toString() + record.getDateTime().getYear();
            String drugName = record.getDrugName();
            Integer quantity = record.getNum();
            Double totalPrice = Double.valueOf(record.getTotalPrice());

            String key = dayMonthYearKey + "-" + drugName;

            if (dailySaleStatisticsMap.containsKey(key)) {
                SaleStatistics statistics = dailySaleStatisticsMap.get(key);
                statistics.setQuantity(statistics.getQuantity() + quantity);
                statistics.setTotalPrice(statistics.getTotalPrice() + totalPrice);
            } else {
                SaleStatistics statistics = new SaleStatistics();
                statistics.setQuantity(quantity);
                statistics.setTotalPrice(totalPrice);
                dailySaleStatisticsMap.put(key, statistics);
            }
        }
        return Result.success(dailySaleStatisticsMap);
    }

    //按天统计昨天每种药品的销售情况  未测试
    @GetMapping("/statisticsDay")
    public Result statisticsDay() {
        // 查询昨天的日期
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime yesterday = currentDateTime.minusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);

        log.info(String.valueOf(yesterday));

        /// 查询数据库获取昨天的销售记录
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Sale::getDateTime, yesterday);
        List<Sale> saleRecords = saleService.list(lambdaQueryWrapper);

        // 统计销售记录
        Map<String, SaleStatistics> saleStatisticsMap = new HashMap<>();
        for (Sale record : saleRecords) {
            String drugName = record.getDrugName();
            Integer quantity = record.getNum();
            Double totalPrice = Double.valueOf(record.getTotalPrice());

            if (saleStatisticsMap.containsKey(drugName)) {
                SaleStatistics statistics = saleStatisticsMap.get(drugName);
                statistics.setQuantity(statistics.getQuantity() + quantity);
                statistics.setTotalPrice(statistics.getTotalPrice() + totalPrice);
            } else {
                SaleStatistics statistics = new SaleStatistics();
                statistics.setQuantity(quantity);
                statistics.setTotalPrice(totalPrice);
                saleStatisticsMap.put(drugName, statistics);
            }
        }

        return Result.success(saleStatisticsMap);
    }

    //热门药品，直接统计最近一年所有药品销售数量多的十种药品 未测试


    @Data
    private class SaleStatistics {
        private Integer quantity;
        private Double totalPrice;
    }
}
